package com.rj.framework.component.tech.captcha;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
     * 内存存储实现
     */
    public  class MemoryCaptchaStore implements CaptchaStore {
        private final Map<String, CaptchaRecord> store = new ConcurrentHashMap<>();
        private final Map<String, List<CaptchaRecord>> targetRecords = new ConcurrentHashMap<>();
        
        @Override
        public void store(CaptchaRecord record) {
            store.put(record.getId(), record);
            
            // 按目标地址存储记录
            String key = getTargetKey(record.getTarget(), record.getType());
            targetRecords.computeIfAbsent(key, k -> new CopyOnWriteArrayList<>())
                         .add(record);
        }
        
        @Override
        public CaptchaRecord get(String id) {
            return store.get(id);
        }
        
        @Override
        public void update(CaptchaRecord record) {
            // 更新存储
            store.put(record.getId(), record);
        }
        
        @Override
        public void remove(String id) {
            CaptchaRecord record = store.remove(id);
            if (record != null) {
                // 从目标记录中移除
                String key = getTargetKey(record.getTarget(), record.getType());
                List<CaptchaRecord> records = targetRecords.get(key);
                if (records != null) {
                    records.remove(record);
                }
            }
        }
        
        @Override
        public void cleanExpired() {
            LocalDateTime now = LocalDateTime.now();
            
            // 清理主存储
            store.values().removeIf(record -> record.getExpireTime().isBefore(now));
            
            // 清理目标记录
            for (List<CaptchaRecord> records : targetRecords.values()) {
                records.removeIf(record -> record.getExpireTime().isBefore(now));
            }
        }
        
        @Override
        public int getRecentCount(String target, CaptchaType type, Duration period) {
            String key = getTargetKey(target, type);
            List<CaptchaRecord> records = targetRecords.get(key);
            if (records == null) {
                return 0;
            }
            
            LocalDateTime cutoff = LocalDateTime.now().minus(period);
            return (int) records.stream()
                .filter(record -> record.getCreateTime().isAfter(cutoff))
                .count();
        }
        
        private String getTargetKey(String target, CaptchaType type) {
            return type + ":" + target;
        }
    }